<template>
  <div class="text-black">
    <PageLayout>
      <template #left>
        <div class="left-bar bg-white">
          <LeftSize>
            <template #leftTop>
              <LeftTop
                v-model:searchName="searchName"
                :recordStates="recordStates"
                :departmentOptions="deptData"
                :leftName="routeName"
                :handle-more-filter="handleMoreFilter"
                :handleFilterOwner="handleFilterOwner"
                @updateSearch="handleSearch"
              ></LeftTop>
            </template>
            <template #leftList>
              <LeftList
                :treeList="treeList"
                :recordStates="recordStates"
                :activeId="activeItem.id"
                @clickItem="handleClickItem"
                @rename="handleRename"
                @move="handleMove"
                @delete="handleDelete"
              ></LeftList>
            </template>
          </LeftSize>
        </div>
      </template>
      <template #nav>
        <!-- {{ deptData }} -->
        <!-- {{ recordStates }} -->
        <HeaderBar
          :status="activeItem.state"
          @showAddDialog="handleShowAddDialog"
          @showCheckDialog="handleShowCheckDialog"
          @revoke="handleRevoke"
          @onPrint="handlePrint"
        ></HeaderBar>
      </template>
      <template #main>
        <div class="main-iframe">
          main{{ activeItem }}
          <IframePage
            :formId="activeItem.instId"
            :recordId="activeItem.id"
            :viewModel="viewModel"
            bizModule="NursingHandbookReal"
            @saveFormData="handleSaveFormData"
            v-if="activeItem.id"
            ref="iframeRef"
          ></IframePage>

          <div v-else class="empty-info"><span class="left-tips">请创建或选择手册</span></div>
        </div>
      </template>
      <template #right>
        <RightSide :processList="processList"></RightSide>
      </template>
    </PageLayout>
    <AddDialog
      ref="createDialog"
      :options="addOption"
      @confirm="handleConfirm"
      @close="handleClose"
    ></AddDialog>
    <updateDialog
      :options="dialogOptions"
      @confirm="handleConfirm"
      @close="handleClose"
    ></updateDialog>
    <moveDialog :options="moveOptions" @confirm="handleConfirm" @close="handleClose"></moveDialog>
    <checkDialog :options="checkOptions" @confirm="handleCheckConfirm"></checkDialog>
    <filterDialog
      :options="filterOptions"
      :departmentOptions="deptData"
      :recordStates="recordStates"
      :positionList="positionList"
      :cateList="formTypeList"
      @confirm="handleFilterConfirm"
    ></filterDialog>
  </div>
</template>
<script setup>
  import {
    computed,
    onBeforeMount,
    onMounted,
    ref,
    reactive,
    nextTick,
    watch,
    defineAsyncComponent,
  } from 'vue';
  import PageLayout from '@/components/PageLayout/index.vue';
  import HeaderBar from '@/components/PageLayout/Side/Header/index.vue';
  import LeftSize from '@/components/PageLayout/Side/Left/index.vue';
  import LeftTop from '@/components/PageLayout/Side/Left/leftTop.vue';
  import LeftList from '@/components/PageLayout/Side/Left/list.vue';
  // import RightSide from '@/components/PageLayout/Side/Right/index.vue';
  // import AddDialog from './components/addDialog.vue';
  // import updateDialog from './components/updateDialog.vue';
  // import moveDialog from './components/moveDialog.vue';
  // import checkDialog from './components/checkDialog.vue';
  // import filterDialog from './components/filterDialog.vue';
  import { useSubMenu } from '@/hooks/useSubMenu/index';
  import {
    deleteHandbookRecord as deleteData,
    postHandbookRecordPage as queryList,
  } from '@/api/handbookRecord/index';

  import { postHandbookTemplatePage } from '@/api/handbookTemplate/index';
  import { getStationList } from '@/api/system/station';
  import { useStore } from 'vuex';
  import { useHandleData } from '@/hooks/useHandleData/index';
  import { useBookList } from '@/hooks/useBookList/index';
  import { useDeptData } from '@/hooks/useDeptData/index';
  import { useProcess } from '@/hooks/useProcess/index';
  // import IframePage from '@/components/IframePage/iframe.vue';
  const AddDialog = defineAsyncComponent(() => import('./components/addDialog.vue'));
  const updateDialog = defineAsyncComponent(() => import('./components/updateDialog.vue'));
  const moveDialog = defineAsyncComponent(() => import('./components/moveDialog.vue'));
  const checkDialog = defineAsyncComponent(() => import('./components/checkDialog.vue'));
  const filterDialog = defineAsyncComponent(() => import('./components/filterDialog.vue'));
  const RightSide = defineAsyncComponent(() =>
    import('@/components/PageLayout/Side/Right/index.vue'),
  );

  const IframePage = defineAsyncComponent(() => import('@/components/IframePage/iframe.vue'));
  import { CHECK_STATUS } from '@/constants/status';

  const store = useStore();
  const allEnums = store.state.app.allEnums;
  const userId = store.getters.userId;
  const { deptData, getDeptData } = useDeptData();
  const showComponent = ref(false);
  const myComponentRef = ref(null);
  const toggleComponent = () => {
    showComponent.value = !showComponent.value;

    // 在组件销毁后重置myComponentRef的值为null
    if (!showComponent.value) {
      myComponentRef.value = null;
    }
  };

  const searchName = ref('');
  const handleMoreFilter = () => {
    filterOptions.visible = true;
  };
  const handleFilterOwner = (val) => {
    handleSearch({ field: 'createBy', value: val ? userId : null });
  };
  const handleRename = (item) => {
    handleUpdate('重命名', item);
  };
  const handleMove = (item) => {
    handleMoveUpdate('移动到', item);
  };
  const addOption = ref({
    width: 760,
    title: '新建',
    visible: false,
    editStatus: false,
    defaultValue: {},
    cate: [],
    templateList: [],
    typeId: '',
  });
  const moveOptions = reactive({
    width: 760,
    title: '移动到',
    visible: false,
    editStatus: false,
    defaultValue: {},
    width: 500,
    cate: [],
    typeId: '',
  });
  let dialogOptions = reactive({
    title: '',
    visible: false,
    defaultValue: {},
    width: 500,
    cate: [],
  });
  const checkOptions = reactive({
    width: 500,
    title: '审核',
    modal: false,
    visible: false,
    top: '30vh',
    cancelText: '取消',
    confirmText: '确定',
    defaultValue: '',
  });
  const handleShowCheckDialog = (row) => {
    checkOptions.visible = true;
    checkOptions.defaultValue = taskInfo.value;
  };
  const filterOptions = reactive({
    width: 500,
    title: '高级筛选',
    modal: false,
    visible: false,
    top: '30vh',
    cancelText: '取消',
    confirmText: '确定',
  });
  // 高级筛选
  const handleFilterConfirm = async (formData) => {
    filterOptions.visible = false;
    console.log('handleFilterConfirm', formData);
    let params = {
      ...formData,
      deptId: formData.deptId ? formData.deptId[formData.deptId.length - 1] : null,
      createTime: !formData?.createTime?.length
        ? null
        : {
            startValue: formData.createTime[0],
            endValue: formData.createTime[1],
          },
    };

    searchParams.value = params;
    await queryData(searchParams.value);
  };
  const viewModel = ref('editor');
  // 新建
  const handleShowAddDialog = () => {
    addOption.value.visible = true;
    addOption.value.title = '新建';
    addOption.value.cate = formTypeList.value;
    addOption.value.defaultValue = {};
    addOption.value.templateList = templateList.value;
    addOption.value.typeId = routerId;
  };

  function handleConfirm() {
    dialogOptions.visible = false;
    addOption.value.visible = false;
    queryData(searchParams.value);
  }

  function handleClose() {
    dialogOptions.visible = false;
    dialogOptions.defaultValue = {};
    moveOptions.visible = false;
    moveOptions.defaultValue = {};
    addOption.value.visible = false;
  }
  // 编辑
  function handleUpdate(title, row) {
    dialogOptions.title = title;
    dialogOptions.visible = true;
    dialogOptions.editStatus = true;
    dialogOptions.defaultValue = JSON.parse(JSON.stringify(row));
    dialogOptions.cate = formTypeList.value;
  }
  // 移动
  function handleMoveUpdate(title, row) {
    moveOptions.title = title;
    moveOptions.visible = true;
    moveOptions.editStatus = true;
    moveOptions.defaultValue = JSON.parse(JSON.stringify(row));
    moveOptions.cate = formTypeList.value;
  }
  // 审核
  function handleCheckConfirm(formData) {
    checkOptions.visible = false;
    console.log('handleCheckConfirm', formData);
    let params = {
      ...formData,
    };
    console.log('params', params);
  }
  async function handleRevoke() {
    await useHandleData(deleteData, { id: row.id }, `请问是否确定撤销这条审核记录`);
  }
  // 删除数据
  async function handleDelete(row) {
    await useHandleData(deleteData, { id: row.id }, `确认删除${row.title}`);
    queryData(searchParams.value);
  }
  // 保存数据
  async function handleSaveFormData(data) {
    console.log('handleSaveFormData', data);
    await queryData(searchParams.value);
    console.log('tableData', tableData);
    let curItem = tableData.value.find((item) => item.id == data.id);
    console.log('curItem', curItem);

    handleClickItem(curItem);
  }

  const templateList = ref([]);
  const activeItem = ref({});
  async function handleClickItem(item) {
    console.log('handleClickItem', item);

    viewModel.value = item.state >= CHECK_STATUS.PENDING_APPROVAL ? 'view' : 'editor';
    activeItem.value = item;
    processList.value = [];
    // toggleComponent();
    if (item?.processId) {
      initProcess(item.processId);
    }
  }
  const { initProcess, processList, taskInfo } = useProcess();

  const { getSubMenu, subMenu, routerId, routeName } = useSubMenu();
  const templateSearchParams = reactive({
    pageSize: 10000,
    pageNum: 1,
    formType: routerId,
  });
  async function queryBookTemplate() {
    let ret = await postHandbookTemplatePage(templateSearchParams);
    if (ret.code === 200) {
      templateList.value = ret.data.records;
    }
  }

  //岗位列表
  const positionList = ref([]);
  async function queryPositionList() {
    let ret = await getStationList();
    if (ret.code === 200) {
      positionList.value = [{ id: '', name: '全部' }].concat(ret.data);
    }
  }

  const formTypeList = ref([]);
  const searchParams = ref({
    // routerId: routerId,
    type: routerId,
    title: '',
  });

  async function handleSearch(params = {}) {
    searchParams.value[params.field] = params.value;
    await queryData(searchParams.value);
  }
  const postMsg = ({ type, data }) => {
    // console.log(type);
    if (!iframeRef.value) return;
    iframeRef.value.contentWindow.postMessage({ type, data }, '*');
  };

  const handlePrint = () => {
    postMsg({ type: 'iframeFormPrint', data: {} });
  };

  const dataField = {
    field: 'list',
  };
  const { queryData, treeList, tableData } = useBookList({ queryList, formTypeList, dataField });
  let recordStates = ref([]);
  onMounted(async () => {
    recordStates.value = [{ code: '', text: '全部' }].concat(allEnums['handbookRecordState']);
    await getSubMenu();
    console.log('routerId', routerId);

    formTypeList.value = subMenu.value?.map((item) => {
      return {
        label: item?.name,
        value: item.id,
        permission: item?.permission,
      };
    });

    await queryData(searchParams.value);
    await getDeptData();

    await queryBookTemplate();
    await queryPositionList();
  });

  // watch processList的长度，并调用toggleComponent销毁
  watch(
    () => processList.value.length,
    (val) => {},
  );
</script>
<style lang="scss" scoped>
  .main-iframe {
    min-width: 500px;
    width: 80%;
    margin: 10px auto;
    display: block;
    background-color: #fff;
    height: 96%;
    overflow: scroll;
    position: relative;
  }
</style>
